<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\RewardApply;
use App\Models\WechatTempMsg;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RewardController extends Controller
{
    public function index(Request $request) {
        $user = $request->user();
        $perPage = $request->get('perPage', 10);
        $query = RewardApply::join('user_project', function($join) {
            $join
                ->on('reward_time_apply.apply_user_id', '=', 'user_project.user_id')
                ->whereRaw('reward_time_apply.project_id = user_project.project_id');
        })->select('reward_time_apply.*', 'user_project.reward_time as work_time')->with('project')->with('user.volunteer');

        $query->where('reward_time_apply.verify_status', '<>', '-1');
        if ($user->type==4 && $request->has('org_id')) {
            $query = $query->where('reward_time_apply.org_id', '=', $request->get('org_id'));
        }
        if ($request->has('status')) {
            $query->where('reward_time_apply.verify_status', '=', $request->get('status'));
        }

        if ($user->type == 3) {
            $projectIds = array_map(function($item) {
                return $item['id'];
            }, Project::select('id')->where('org_id', '=', $user->org->id)->get()->toArray());

            $query->whereIn('reward_time_apply.project_id', $projectIds);
        } else if ($user->type == 2) {
            $projectIds = array_map(function($item) {
                return $item['id'];
            }, Project::select('id')->where('team_id', '=', $user->team->id)->get()->toArray());

            $query->whereIn('reward_time_apply.project_id', $projectIds);
        }

        $query->orderBy('reward_time_apply.created_at', 'desc');

//        echo $query->toSql();exit;

        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);

    }

    public function accept(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $user = $request->user();
        $nodes = RewardApply::whereIn('id', $ids)->where('verify_status', '=', '0')->get();
        $result = RewardApply::whereIn('id',  $ids)->where('verify_status', '=', '0')->update(['verify_status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            Log::info($nodes);

            foreach ($nodes as $node) {
                Log::info($node);

                $node->syncRewardTime();

                //微信模版消息，申请补录通过
                WechatTempMsg::add(7, ['reward_time_apply_id'=>$node->id]);
            }
            $rewardInfos = RewardApply::with(['project.org'])->whereIn('id',  $ids)->get();
//            Log::info($rewardInfos);

            $data = [];
            foreach($rewardInfos as $item)
            {
                $content = '【'.$item->project->org->name.'】您申请项目【'.$item->project->name.'】的补录志愿时长'
                    .$item->reward_time.'小时，补录成功，获得志愿时长'.$item->reward_time.'小时';
                $data[] = array('from_user_id'=>$user->id,
                    'title' => $request->get('title', ''),
                    'to_user_id'=>$item->apply_user_id,
                    'type' => 1,
                    'content' => $content,);
            }
//            Log::info($data);
            // 发送站内信
            DB::table('user_message')->insert($data);

            return $this->returnJSON($ids, 0, '审核通过');
        } else {

            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function reject(Request $request, $id)
    {
        $this->validate($request, [
            'reason' => 'required'
        ]);
        $user = $request->user();
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $result = RewardApply::whereIn('id',  $ids)->where('verify_status', '=', '0')->update([
            'verify_status' => 2,
            'verify_msg' => $request->get('reason')
        ]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            $rewardInfos = RewardApply::with(['project.org'])->whereIn('id',  $ids)->get();
            $nodes = [];
            foreach($rewardInfos as $item)
            {
                //微信模版消息，申请补录通过
                WechatTempMsg::add(8, ['reward_time_apply_id'=>$item->id]);

                $content = '【'.$item->project->org->name.'】您申请项目【'.$item->project->name.'】的补录志愿时长'.$item->reward_time.'小时，未通过审核';
                $nodes[] = array('from_user_id'=>$user->id,
                    'title' => $request->get('title', ''),
                    'to_user_id'=>$item->apply_user_id,
                    'type' => 1,
                    'content' => $content,);
            }
            // 发送站内信
            DB::table('user_message')->insert($nodes);
            return $this->returnJSON($ids, 0, '驳回成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
}
